// 新增图书
// 1.获取豆瓣信息
// 2.入库
const { mysql } = require('../qcloud')
const axios = require('axios')
module.exports = async ctx => {
    const { isbn, openId } = ctx.request.body
    var isExist = await mysql('books')
        .select()
        .where('isbn', isbn)
    if (isExist.length) {
        ctx.state = {
            code: -1,
            data: {
                msg: '图书已存在'
            }
        }
        return
    }
    if (isbn && openId) {
        const url = 'https://douban.uieee.com/v2/book/isbn/' + isbn
        const bookInfo = await axios.get(url)
        const rate = bookInfo.data.rating.average
        const { title, image, alt, publisher, summary, price } = bookInfo.data
        const tags = bookInfo.data.tags
            .map(v => {
                return `${v.title} ${v.count}`
            })
            .join(',')
        const author = bookInfo.data.author.join(',')
        // const response = {
        //     isbn,
        //     openid: openId,
        //     rate: bookInfo.data.rating.average,
        //     title,
        //     image,
        //     alt,
        //     publisher,
        //     summary,
        //     price,
        //     tags,
        //     author
        // }
        // ctx.state.data = response

        try {
            await mysql('books').insert({
                isbn,
                openid: openId,
                rate,
                title,
                image,
                alt,
                publisher,
                summary,
                price,
                tags,
                author
            })
            ctx.state.data = {
                title,
                msg: 'success'
            }
        } catch (e) {
            ctx.state = {
                code: -1,
                data: {
                    msg: '新增失败' + e.sqlMessage
                }
            }
        }
    }
}
